<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Http\Utils\Time;

class ReleaseController extends Controller
{


    /*************************通知********************************/
    /**
     *
     */
    public function fileaddnotice()
    {
        return view('home.release.notice.filenotice', [

        ]);
    }

    /**
     * 获取一条
     * @param $id
     * @return \App\Http\Utils\Response
     */
    public function getOneNotice($id)
    {
        $dt = DB::table('notice')
            ->join(
                'user',
                'user.id', '=','notice.user_id'
            )
            ->where([
                ['notice.id', '=', $id]
            ])
            ->select([
                'user.nickName',
                'notice.user_id',
                'notice.id',
                'notice.template',
                'notice.title',
                'notice.content',
                'notice.pictures',
                'notice.reference_number',
                'notice.unit_generation_word',
                'notice.is_forwarding',
                'notice.keyword',
                'notice.update_time',
                'notice.create_time',
            ])
            ->first();
        if (is_null($dt)){
            return $this->json('', 417, '没找到这个通知');
        };
        $dt->pictures = explode(',', $dt->pictures);
        $dt->update_time = date('Y-m-d H:s:i', $dt->update_time);
        $dt->create_time = date('Y-m-d H:s:i', $dt->create_time);
        return $this->json($dt,200,'ok');
    }

    /**
     * 添加
     * @param Request $request
     * @return \App\Http\Utils\Response|array
     */
    public function addNotice(Request $request)
    {
        $data = $request->all();
        $rules = [
            'template'      => 'required',
            'title'         => 'required',
            'content'       => 'required',
            'user_id'       => 'required',
            'is_forwarding' => 'required',
        ];
        $messages = [
            'template.required'      => '图片模板不能为空',
            'title.required'         => '请填写标题',
            'content.required'       => '请填写内容',
            'user_id.required'       => '署名不能为空',
            'is_forwarding.required' => '是否转发不能为空',
        ];
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            return $this->json('',417,$validator->getMessageBag()->getMessages());
        }
        $id = DB::table('notice')->insertGetId([
            'template'             => $data['template'],
            'title'                => $data['title'],
            'content'              => $data['content'],
            'pictures'             => array_key_exists('pictures', $data) ? implode(',', $data['pictures']) : '',
            'user_id'              => $data['user_id'],
            'is_forwarding'        => $data['is_forwarding'],
            'reference_number'     => array_key_exists('reference_number', $data) ? $data['reference_number'] : '',
            'unit_generation_word' => array_key_exists('unit_generation_word', $data) ? $data['unit_generation_word'] : '',
            'keyword'              => array_key_exists('keyword', $data) ? $data['keyword'] : '',
            'update_time'          => Time::current(),
            'create_time'          => Time::current(),
        ]);
        return $this->json(['type' =>'notice', 'id' => $id],200,'ok');
    }

    /**
     * 修改
     * @param Request $request
     * @param $id
     * @return \App\Http\Utils\Response
     */
    public function updateNotice(Request $request, $id)
    {
        $data = $request->all();
        $rules = [
            'template'      => 'required',
            'title'         => 'required',
            'content'       => 'required',
            'user_id'       => 'required',
            'is_forwarding' => 'required',
        ];
        $messages = [
            'template.required'      => '图片模板不能为空',
            'title.required'         => '请填写标题',
            'content.required'       => '请填写内容',
            'user_id.required'       => '署名不能为空',
            'is_forwarding.required' => '是否转发不能为空',
        ];
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            return $this->json('',417,$validator->getMessageBag()->getMessages());
        }
        DB::table('notice')
            ->where([['id', '=', $id]])
            ->update([
                'template'             => $data['template'],
                'title'                => $data['title'],
                'content'              => $data['content'],
                'pictures'             => array_key_exists('pictures', $data) ? implode(',', $data['pictures']) : '',
                'user_id'              => $data['user_id'],
                'is_forwarding'        => $data['is_forwarding'],
                'reference_number'     => array_key_exists('reference_number', $data) ? $data['reference_number'] : '',
                'unit_generation_word' => array_key_exists('unit_generation_word', $data) ? $data['reference_number'] : '',
                'keyword'              => array_key_exists('keyword', $data) ? $data['keyword'] : '',
                'update_time'          => Time::current(),
            ]);
        return $this->json('',200,'ok');
    }

    /**************************活动****************************************/
    public function fileaddActivity()
    {
        return view('home.release.activity.fileactivity', [

        ]);
    }

    public function getOneActivity($id)
    {
        $dt = DB::table('activity')
            ->join(
                'user',
                'user.id','=','activity.user_id'
            )
            ->where([
                ['activity.id', '=', $id]
            ])
            ->select([
                'user.nickName',
                'activity.user_id',
                'activity.id',
                'activity.template',
                'activity.title',
                'activity.content',
                'activity.pictures',
                'activity.reference_number',
                'activity.unit_generation_word',
                'activity.is_forwarding',
                'activity.keyword',
                'activity.people_num',
                'activity.address',
                'activity.address_info',
                'activity.is_user_name',
                'activity.is_user_tel',
                'activity.update_time',
                'activity.create_time',
            ])
            ->first();
        if (is_null($dt)){
            return $this->json('', 417, '没找到这个活动');
        };
        $dt->update_time = date('Y-m-d H:s:i', $dt->update_time);
        $dt->create_time = date('Y-m-d H:s:i', $dt->create_time);
        $dt->pictures = explode(',', $dt->pictures);
        $dt->activity_custom_title = DB::table('activity_custom_title')
            ->where([
                ['activity_id', '=', $id]
            ])
            ->get()->toArray();

        return $this->json($dt,200,'ok');
    }

    public function addActivity(Request $request)
    {
        $data = $request->all();
        $rules = [
            'template'      => 'required',
            'title'         => 'required',
            'content'       => 'required',
            'user_id'       => 'required',
            'is_forwarding' => 'required',
        ];
        $messages = [
            'template.required'      => '图片模板不能为空',
            'title.required'         => '请填写标题',
            'content.required'       => '请填写内容',
            'user_id.required'       => '署名不能为空',
            'is_forwarding.required' => '是否转发不能为空',
        ];
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            return $this->json('',417,$validator->getMessageBag()->getMessages());
        }
        DB::beginTransaction();
        try {
            $id = DB::table('activity')->insertGetId([
                'template'             => $data['template'],
                'title'                => $data['title'],
                'content'              => $data['content'],
                'user_id'              => $data['user_id'],
                'pictures'             => array_key_exists('pictures', $data) ? implode(',', $data['pictures']) : '',
                'is_forwarding'        => array_key_exists('is_forwarding', $data) ? $data['is_forwarding'] : '',
                'is_user_name'         => array_key_exists('is_user_name', $data) ? $data['is_user_name'] : 'false',
                'is_user_tel'          => array_key_exists('is_user_tel', $data) ? $data['is_user_tel'] : 'false',
                'reference_number'     => array_key_exists('reference_number', $data) ? $data['reference_number'] : '',
                'unit_generation_word' => array_key_exists('unit_generation_word', $data) ? $data['reference_number'] : '',
                'keyword'              => array_key_exists('keyword', $data) ? $data['keyword'] : '',
                'people_num'           => array_key_exists('people_num', $data) ? $data['people_num'] : '',
                'address'              => array_key_exists('address', $data) ? $data['address'] : '',
                'address_info'         => array_key_exists('address_info', $data) ? $data['address_info'] : '',
                'update_time'          => Time::current(),
                'create_time'          => Time::current(),
            ]);
            foreach ($data['activity_custom_title'] as $value) {
                DB::table('activity_custom_title')
                    ->insert([
                        'activity_id' => $id,
                        'title'       => $value,
                    ]);
            }
            DB::commit();
            return $this->json('',200,'ok');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->json('',500,'服务器错误');
        }
    }

    public function updateActivity(Request $request, $id)
    {
        $data = $request->all();
        $rules = [
            'template'      => 'required',
            'title'         => 'required',
            'content'       => 'required',
            'user_id'       => 'required',
            'is_forwarding' => 'required',
        ];
        $messages = [
            'template.required'      => '图片模板不能为空',
            'title.required'         => '请填写标题',
            'content.required'       => '请填写内容',
            'user_id.required'       => '署名不能为空',
            'is_forwarding.required' => '是否转发不能为空',
        ];
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            return $this->json('',417,$validator->getMessageBag()->getMessages());
        }
        DB::beginTransaction();
        try {
            DB::table('activity')
                ->where([
                    ['id', '=', $id]
                ])
                ->update([
                    'template'             => $data['template'],
                    'title'                => $data['title'],
                    'content'              => $data['content'],
                    'pictures'             => array_key_exists('pictures', $data) ? implode(',', $data['pictures']) : '',
                    'user_id'              => $data['user_id'],
                    'is_forwarding'        => array_key_exists('is_forwarding', $data) ? $data['is_forwarding'] : '',
                    'is_user_name'         => array_key_exists('is_user_name', $data) ? $data['is_user_name'] : 'false',
                    'is_user_tel'          => array_key_exists('is_user_tel', $data) ? $data['is_user_tel'] : 'false',
                    'reference_number'     => array_key_exists('reference_number', $data) ? $data['reference_number'] : '',
                    'unit_generation_word' => array_key_exists('unit_generation_word', $data) ? $data['reference_number'] : '',
                    'keyword'              => array_key_exists('keyword', $data) ? $data['keyword'] : '',
                    'people_num'           => array_key_exists('people_num', $data) ? $data['people_num'] : '',
                    'address'              => array_key_exists('address', $data) ? $data['address'] : '',
                    'update_time'          => Time::current(),
                ]);

            $activity_custom_titles = DB::table('activity_custom_title')
                ->where([
                    ['activity_id', '=', $id]
                ])->get();
            foreach ($activity_custom_titles as $k => $v) {
                DB::table('activity_custom_title')
                    ->where([
                        ['id', '=', $v->id]
                    ])->update([
                        'title' => $data['activity_custom_title'][$k]
                    ]);
            }

            $activity_custom_title_num = count($activity_custom_titles);
            $dt_activity_custom_title_num = count($data['activity_custom_title']);
            foreach ($data['activity_custom_title'] as $k => $v) {
                if ($dt_activity_custom_title_num > $activity_custom_title_num) {
                    DB::table('activity_custom_title')
                        ->insert([
                            'activity_id' => $id,
                            'title'       => $v,
                        ]);
                }
            }
            DB::commit();
            return $this->json('',200,'ok');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->json('',500,'服务器错误');
        }
    }

    /**
     * 活动报名页
     */
    public function fileSignUp($id)
    {
        $dt = DB::table('activity')
            ->where([
                ['id', '=', $id]
            ])->first([
                'id',
                'is_user_name',
                'is_user_tel',
            ]);
        if (is_null($dt)){
            return $this->json('', 417, '没找到这个活动');
        };
        $dt->activity_custom_titles = DB::table('activity_custom_title')
            ->where([
                ['activity_id', '=', $id]
            ])->get()->toArray();

        return view('home.release.activity.filesignup', [
            'dt' =>$dt
        ]);
        return $this->json($dt, 200, 'ok');
    }

    /**
     * 参加活动
     * @param Request $request
     * @param $id
     */
    public function signUp(Request $request, $id)
    {
        $data = $request->all();

        //判断是否已加入该活动
        $isc = DB::table('activity_sign_up')
            ->where([
                ['activity_id', '=', $id],
                ['user_id', '=', $data['user_id']],
            ])->first();
        if (!empty($isc)) {
            return $this->json('',417,'已参加过该活动');
        }

        DB::beginTransaction();
        try {
            foreach ($data['activity_custom_title_ids'] as $k => $v) {
                DB::table('activity_custom')
                    ->insert([
                        'activity_id'              => $id,
                        'user_id'                  => $data['user_id'],
                        'activity_custom_title_id' => $v,
                        'content'                  => $data['content'][$k],
                        'update_time'              => Time::current(),
                        'create_time'              => Time::current(),
                    ]);

            }
            DB::table('activity_sign_up')
                ->insert([
                    'activity_id'  => $id,
                    'user_id'     => $data['user_id'],
                    'user_name'   => $data['user_name'],
                    'user_tel'    => $data['user_tel'],
                    'create_time' => Time::current(),
                    'update_time' => Time::current(),
                ]);
            DB::commit();
            return $this->json('', 200, 'ok');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->json('', 500, '服务器错误');
        }
    }


    /**************************投票**********************************/
    public function fileVote()
    {
        return view('home.release.vote.filevote', [

        ]);
    }

    /**
     * 添加投票
     * @param Request $request
     * @return \App\Http\Utils\Response
     */
    public function addVote(Request $request)
    {
        $data = $request->all();
        $rules = [
            'type'           => 'required',
            'title'          => 'required',
            'content'        => 'required',
            'vote_options'   => 'required|array',
            'min_choose_num' => 'required|numeric|min:1',
            'max_choose_num' => 'required|numeric|min:1',
            'user_id'        => 'required',
        ];
        $messages = [
            'type.required'           => '请选择投票类型',
            'title.required'          => '请填写标题',
            'content.required'        => '请填写内容',
            'vote_options.required'   => '选项不能为空',
            'min_choose_num.required' => '最少选择个数不能为空',
            'min_choose_num.numeric'  => '最少选择数为数字',
            'min_choose_num.min'      => '最少选择个数大于等于1',
            'max_choose_num.required' => '最多选择个数不能为空',
            'max_choose_num.numeric'  => '最多选择数为数字',
            'max_choose_num.min'      => '最多选择个数大于等于1',
            'user_id.required'        => '发起人不能为空',
        ];
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            return $this->json('',417,$validator->getMessageBag()->getMessages());
        }

        if ($data['min_choose_num'] > $data['max_choose_num']) {
            return $this->json('',417,'最少选择不能大于最大选择');
        }
        DB::beginTransaction();
        try {
            $id = DB::table('vote')
                ->insertGetId([
                    'type'            => $data['type'],
                    'title'           => $data['title'],
                    'content'         => $data['content'],
                    'user_id'         => $data['user_id'],
                    'min_choose_num'  => $data['min_choose_num'],
                    'max_choose_num'  => $data['max_choose_num'],
                    'is_multi_select' => array_key_exists('is_multi_select', $data) ? $data['is_multi_select'] : 'false',
                    'is_anonymous'    => array_key_exists('is_anonymous', $data) ? $data['is_anonymous'] : 'false',
                    'is_forwarding'   => array_key_exists('is_forwarding', $data) ? $data['is_forwarding'] : 'false',
                    'as_of_time'      => array_key_exists('as_of_time', $data) ? $data['as_of_time'] : Time::current(),
                    'update_time'     => Time::current(),
                    'create_time'     => Time::current(),
                ]);
                foreach ($data['vote_options'] as $v) {
                    DB::table('vote_options')
                        ->insert([
                            'vote_id' => $id,
                            'options' => $v,
                        ]);
                }

            DB::commit();
            return $this->json('', 200, 'ok');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->json('', 500, '服务器错误');
        }
    }

    /**
     * 获取一条信息
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getOneVote($id)
    {
        $dt = DB::table('vote')
            ->join(
                'user',
                'user.id', '=','vote.user_id'
            )
            ->where([
                ['vote.id', '=', $id]
            ])
            ->select([
                'user.nickName',
                'vote.id',
                'vote.type',
                'vote.title',
                'vote.content',
                'vote.user_id',
                'vote.is_multi_select',
                'vote.min_choose_num',
                'vote.max_choose_num',
                'vote.is_anonymous',
                'vote.is_forwarding',
                'vote.as_of_time',
                'vote.update_time',
                'vote.create_time',
            ])
            ->first();
        if (is_null($dt)){
            return $this->json('', 417, '没找到这个投票');
        };
        $dt->update_time = date('Y-m-d H:s:i', $dt->update_time);
        $dt->create_time = date('Y-m-d H:s:i', $dt->create_time);
        $dt->vote_options = DB::table('vote_options')
            ->where([
                ['vote_id', '=', $id]
            ])
            ->get()->toArray();

        return $this->json($dt, 200, 'ok');

        /*return view('home.release.vote.upfilevote', [
            'dt' => $dt
        ]);*/
    }

    /**
     * 修改投票
     * @param Request $request
     * @param $id
     */
    public function upVote(Request $request, $id)
    {
        $data = $request->all();
        $rules = [
            'type'           => 'required',
            'title'          => 'required',
            'content'        => 'required',
            'vote_options'   => 'required|array',
            'min_choose_num' => 'required|numeric|min:1',
            'max_choose_num' => 'required|numeric|min:1',
            'user_id'        => 'required',
        ];
        $messages = [
            'type.required'           => '请选择投票类型',
            'title.required'          => '请填写标题',
            'content.required'        => '请填写内容',
            'vote_options.required'   => '选项不能为空',
            'min_choose_num.required' => '最少选择个数不能为空',
            'min_choose_num.numeric'  => '最少选择数为数字',
            'min_choose_num.min'      => '最少选择个数大于等于1',
            'max_choose_num.required' => '最多选择个数不能为空',
            'max_choose_num.numeric'  => '最多选择数为数字',
            'max_choose_num.min'      => '最多选择个数大于等于1',
            'user_id.required'        => '发起人不能为空',
        ];
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            return $this->json('',417,$validator->getMessageBag()->getMessages());
        }

        if ($data['min_choose_num'] > $data['max_choose_num']) {
            return $this->json('',417,'最少选择不能大于最大选择');
        }
        DB::beginTransaction();
        try {
            $id = DB::table('vote')
                ->where([
                    ['id', '=', $id]
                ])
                ->update([
                    'type'            => $data['type'],
                    'title'           => $data['title'],
                    'content'         => $data['content'],
                    'user_id'         => $data['user_id'],
                    'min_choose_num'  => $data['min_choose_num'],
                    'max_choose_num'  => $data['max_choose_num'],
                    'is_multi_select' => array_key_exists('is_multi_select', $data) ? $data['is_multi_select'] : 'false',
                    'is_anonymous'    => array_key_exists('is_anonymous', $data) ? $data['is_anonymous'] : 'false',
                    'is_forwarding'   => array_key_exists('is_forwarding', $data) ? $data['is_forwarding'] : 'false',
                    'as_of_time'      => array_key_exists('as_of_time', $data) ? $data['as_of_time'] : Time::current(),
                    'update_time'     => Time::current(),
                    'create_time'     => Time::current(),
                ]);
            foreach ($data['vote_options'] as $k => $v) {
                if ($data['vote_options_ids'][$k]) {
                    DB::table('vote_options')
                        ->where([
                            ['id', '=', $data['vote_options_ids'][$k]]
                        ])
                        ->update([
                            'vote_id' => $id,
                            'options' => $v,
                        ]);
                } else {
                    DB::table('vote_options')
                        ->insert([
                            'vote_id' => $id,
                            'options' => $v,
                        ]);
                }
            }
            DB::commit();
            return $this->json('', 200, 'ok');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->json('', 500, '服务器错误');
        }
    }


    /**
     * 用户投票页
     */
    public function fileUserVote($id)
    {
        $dt = DB::table('vote')
            ->where([
                ['id', '=', $id]
            ])->first();
        if (is_null($dt)){
            return $this->json('', 417, '没找到这个投票');
        };
        $dt->vote_options = DB::table('vote_options')
            ->where([
                ['vote_id', '=', $id]
            ])->get()->toArray();
        dump($id);
        dump($dt);
        return view('home.release.vote.fileuservote', [
            'dt' => $dt
        ]);
    }

    /**
     * 用户投票
     */
    public function userVote(Request $request, $id)
    {
        $data = $request->all();
        $isc = DB::table('vote_user')
            ->where([
                ['vote_id', '=', $id],
                ['user_id', '=', $data['user_id']],
            ])->first();
        if (!empty($isc)) {
            return $this->json('', 417, '你已经投过票');
        }

        DB::beginTransaction();
        try {
            foreach ($data['vote_options_ids'] as $v) {
                DB::table('vote_user')
                    ->insert([
                        'vote_id'         => $id,
                        'user_id'         => $data['user_id'],
                        'vote_options_id' => $v,
                        'answer'          => $data['answer_' . $v],
                        'update_time'     => Time::current(),
                        'create_time'     => Time::current(),
                    ]);
            }
            DB::commit();
            return $this->json('', 200, 'ok');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->json('', 500, '服务器错误');
        }
    }

    /***************************祝福语*****************************************/
    /**
     * 获取所有祝福语类型
     * @return \App\Http\Utils\Response
     */
    public function getBlessingTextTypeList()
    {
        $dt = DB::table('blessing_text_type')
            ->get()->toArray();
        return $this->json($dt, 200, 'ok');
    }

    /**
     * 获取后台传的祝福语
     * @param $id
     * @return \App\Http\Utils\Response
     */
    public function getOneBlessingText($id)
    {
        $dt = DB::table('blessing_text as bt')
            ->join(
                'blessing_text_type as btt',
                'id', '=', 'bt.blessing_text_type_id',
                'left'
            )
            ->select([
                'bt.id',
                'bt.blessing_text_type_id',
                'bt.content',
                'btt.name as blessing_text_type_name',
                'btt.path',
            ])
            ->where([
                ['bt.id', '=', $id]
            ])->first();
        return $this->json($dt, 200, 'ok');
    }

    /**
     * 通过类型id获取后台传的祝福语
     * @param $id
     * @return \App\Http\Utils\Response
     */
    public function getOneBlessingTextByTypeId($id)
    {
        $dt = DB::table('blessing_text')
            ->where('blessing_text_type_id', '=', $id)
            ->get()->toArray();
        return $this->json($dt, 200, 'ok');
    }

    /**
     * 获取用户添加的祝福语
     * @return \App\Http\Utils\Response
     */
    public function getOneBlessing()
    {
        $dt = DB::table('blessing_text_type')
            ->get()->toArray();
        if (is_null($dt)){
            $dt = [];
        }
        foreach ($dt as $k=>$v){
            $dt[$k]->blessing_text = DB::table('blessing_text')
                ->where('blessing_text_type_id','=',$v->id)
                ->get()->toArray();
        }
        return $this->json($dt, 200, 'ok');
    }

    public function fileblessing()
    {
        return view('home.release.blessing.fileblessing', [

        ]);
    }

    /**
     * 添加祝福语
     * @param Request $request
     * @return \App\Http\Utils\Response
     */
    public function addBlessing(Request $request)
    {
        $data = $request->all();
        $rules = [
            'type'           => 'required',
            'title'          => 'required',
        ];
        $messages = [
            'type.required'           => '请选择投票类型',
            'title.required'          => '请填写标题',
        ];
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            return $this->json('',417,$validator->getMessageBag()->getMessages());
        }

        dump($data);
    }

}